package com.smart.system.service.impl;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.smart.common.config.HttpClientTemplate;
import com.smart.common.config.MobileUnitConfig;
import com.smart.common.core.domain.*;
import com.smart.common.utils.DateUtils;
import com.smart.common.utils.StringUtils;
import com.smart.common.utils.http.HttpUtils;
import com.smart.system.domain.AreaLocation;
import com.smart.system.domain.Car;
import com.smart.system.service.ICarService;
import com.smart.system.service.IMobileUnitService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

@Service
public class MobileUnitServiceImpl implements IMobileUnitService {

    @Autowired
    private MobileUnitConfig mobileUnitConfig;
    @Autowired
    private HttpClientTemplate httpClientTemplate;

    @Autowired
    private ICarService carService;

    @Override
    public MobileResult getSession(String account, String password) {
        Map params = new HashMap();
        params.put("account",account);
        params.put("password",password);
        String s = HttpUtils.sendGet(mobileUnitConfig.getBaseUrl()+mobileUnitConfig.getLoginUrl()+"?account="+account+"&password="+password);
        MobileResult res = JSON.parseObject(s, MobileResult.class);
        return res;
    }

    @Override
    public MobileResult getSession() {
        return getSession(mobileUnitConfig.getAccount(), mobileUnitConfig.getPassword());
    }

    @Override
    public String getVideoUrl(String carNumber) {
        return mobileUnitConfig.getBaseUrl()+mobileUnitConfig.getVideoUrl()+"?lang=zh&devIdno="+carNumber+"&jsession="+getSession().getJsession();
    }

    @Override
    public AreaLocation getLocation(String carNumber) {
        String s = HttpUtils.sendGet(mobileUnitConfig.getBaseUrl()+mobileUnitConfig.getLocationUrl() + "?jsession=" + getSession().getJsession() + "&vehiIdno=" + carNumber + "&toMap=2&currentPage=1&pageRecords=1&geoaddress=0");
        Location res = JSON.parseObject(s, Location.class);
        Location.Info info = res.getInfos().get(0);
        AreaLocation areaLocation = new AreaLocation();
        areaLocation.setNumber(carNumber);
        areaLocation.setLatitude(String.valueOf(info.getMlat()));
        areaLocation.setLongitude(String.valueOf(info.getMlng()));
        return areaLocation;
    }

    @Override
    public List<AreaLocation> getLocation(List<String> carNumbers) {
        String s = HttpUtils.sendGet(mobileUnitConfig.getBaseUrl()+mobileUnitConfig.getLocationUrl() + "?jsession=" + getSession().getJsession() + "&vehiIdno=" + carNumbers.stream().collect(Collectors.joining(",")) + "&toMap=2&currentPage=1&pageRecords=1&geoaddress=0");
        Location res = JSON.parseObject(s, Location.class);
        List<Location.Info> infos = res.getInfos();
        List<AreaLocation> areaLocations = new LinkedList<AreaLocation>();
        for (Location.Info info : infos) {
            for (String carNumber : carNumbers) {
                if (carNumber.equals(info.getVi())) {
                    AreaLocation areaLocation = new AreaLocation();
                    areaLocation.setNumber(info.getVi());
                    areaLocation.setLatitude(String.valueOf(info.getMlat()));
                    areaLocation.setLongitude(String.valueOf(info.getMlng()));
                    areaLocations.add(areaLocation);
                }
            }
        }
        return areaLocations;
    }

    @Override
    public Integer getDeviceOnline(String carNumber) {
        String s = HttpUtils.sendGet(mobileUnitConfig.getBaseUrl()+mobileUnitConfig.getIsOnlineUrl() + "?jsession=" + getSession().getJsession() + "&vehiIdno=" + carNumber);
        OnlineResult r = JSON.parseObject(s, OnlineResult.class);
        if (r.getResult()==0) {
            OnlineResult.OnlineDevice onlineDevice = r.getOnlines().get(0);
            return onlineDevice.getOnline()==1?0:1;
        }
        return null;
    }

    @Override
    public List<String> getDeviceOnline(List<String> carNumbers) {
        //清除掉不对的数据,并录入
        String s = HttpUtils.sendGet(mobileUnitConfig.getBaseUrl()+mobileUnitConfig.getIsOnlineUrl()
                + "?jsession=" + getSession().getJsession()
                + "&vehiIdno=" + carNumbers.stream().filter(str -> str!= null && !str.equals("")).collect(Collectors.joining(",")));
        OnlineResult r = JSON.parseObject(s, OnlineResult.class);
        List<String> res = new LinkedList<>();
        if (r.getResult()==0) {
            for (OnlineResult.OnlineDevice online : r.getOnlines()) {
                if(online.getOnline()==1){
                    res.add(online.getDid());
                    break;
                }
            }
            return res;
        }
        return Collections.emptyList();
    }

    /**
     * 获取里程报表
     * @param carNumbers
     * @param startTime
     * @param endTime
     * @return
     * https://218.93.208.93:8888/StandardApiAction_getOilTrackDetail.action?
     * jsession=fec0445551334da89b8a2b7107ae7c4e
     * &vehiIdno=018302077524
     * &begintime=2020-05-18 00:00:00
     * &endtime=2020-06-17 23:59:59
     * &toMap=2
     * &currentPage=1
     * &pageRecords=10
     */
    @Override
    public List<VehicleTripInfo> getMileageStatement(List<String> carNumbers, String startTime, String endTime) {
        //todo 设备会有不在线的情况,但是不在线好像没有什么影响,后续再作考虑
        String beginTimeStr =  DateUtils.parseStrToUrlStrDate(startTime,"00:00:00");
        String endTimeStr =  DateUtils.parseStrToUrlStrDate(endTime,"23:59:59");
        String s1 = mobileUnitConfig.getBaseUrl()+mobileUnitConfig.getMileageStatementUrl()
                +"?jsession=" + getSession().getJsession()
                +"&vehiIdno=" + carNumbers.stream().collect(Collectors.joining(","))
                +"&begintime="+beginTimeStr+"&endtime="+endTimeStr
                +"&toMap=2"
                ;
        String s = HttpUtils.sendGet(s1);
        if(StringUtils.isEmpty(s)){
            return Collections.emptyList();
        }
        JSONObject jsonObject = JSON.parseObject(s);
        JSONArray infos = jsonObject.getJSONArray("infos");
        if(infos!=null){
            return infos.toList(VehicleTripInfo.class);
        }
        return Collections.emptyList();
    }

    @Override
    public List<DeviceInfo> getCarInfoDetails(List<String> carNumbers) {
        String url = mobileUnitConfig.getBaseUrl()+mobileUnitConfig.getCarInfoDetailsUrl() + "?" + "jsession=" + getSession().getJsession() + "&vehiIdno=" + carNumbers.stream().collect(Collectors.joining(",")) + "&language=zh";
        String s = HttpUtils.sendGet(url);
        JSONObject jsonObject = JSON.parseObject(s);
        if (jsonObject.getInteger("result")==0) {
            return jsonObject.getJSONArray("status").toList(DeviceInfo.class);
        }
        return null;
    }
}
